package com.sunwayhorizo.health.business.registries.person.query;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TemporalType;

import org.jboss.seam.annotations.Name;

import com.sunwayhorizo.health.common.DateUtil;
import com.sunwayhorizo.health.common.ListUtil;
import com.sunwayhorizo.health.common.StrUtil;
import com.sunwayhorizo.health.hl7.common.Hl7Exception;
import com.sunwayhorizo.health.hl7.rim.Person;

@Name("PersonQuery")
@Stateless
public class PersonQuery implements PersonQueryLocal
{

    @PersistenceContext(unitName = "sunwayhealth")
    private EntityManager em;
    

    @SuppressWarnings("unchecked")
    public Person findSamePerson(String personName, String sex, String birthDate) throws Hl7Exception
    {
        if (StrUtil.isEmpty(personName) && StrUtil.isEmpty(sex))  return null;
        StringBuilder jbql = new StringBuilder();
        String cond = "";
        jbql.append(" select p from Person p ");
        jbql.append(" left join p.entyNamesList nameList left join nameList.entyNamePartsList partList");
        cond += " where partList.literal='" + personName + "'";
        jbql.append(" left join p.entyCdSetsList cdSet ");
        cond += " and cdSet.conceptCode='" + sex + "'";
        if (StrUtil.isNotEmpty(birthDate))
        {
            cond += " and p.lsBirthDateTs=?1";
        }
        Query query = em.createQuery(jbql.toString() + cond);
        if (StrUtil.isNotEmpty(birthDate))
        {
            query.setParameter(1, DateUtil.getDateBy3String(birthDate), TemporalType.TIMESTAMP);
        }
        List<Person> persons = query.getResultList();
        if (ListUtil.isNotEmpty(persons))
        {
            return persons.get(0);
        }
        return null;
    }
   
}
